$(document).ready(function() {
  citylist = $('#city_list');
  removeButtonElement = '<input type="button" value="-" class="remove-city-button">'
  citylist.children('').each(function() {
    $(this).append(removeButtonElement);
    $(this).children('.remove-city-button').click(function() {
      removeCity($(this).parent().attr('cityid'));
    })
  })
    
  $('#city_form_button').click(function() {
    var dataString = $('#city_form').serialize();
    $.post(addCityUrl,
      {data: dataString},
      function(msg){
        citylist.append('<li cityid="' + msg.city_id + '">' + msg.city_name + '</li>')
        citylist.children(':last').append(removeButtonElement)
        citylist.children(':last').children('.remove-city-button').click(function() {
          removeCity(msg.city_id);
        });
        $('#city_form select option[value="' + msg.city_id + '"]').remove();           
      })
  })
});

function removeCity(cityId) {
  $.post(removeCityUrl,
    {cityid: cityId},
    function(msg){
      citylist.children('[cityid="' + cityId + '"]').remove();
      elem = '<option value="' + cityId + '">' + msg.city_name + '</option>'
      if (msg.insertAfter != -1) {
        insertAfter = $('#city_form select option[value="' + msg.insertAfter + '"]');
        insertAfter.after(elem);
      }
      else {
        insertAfter = $('#city_form select');
        insertAfter.prepend(elem);
      }        
    })
}
